<template>
    <Transition>
        <div class="contain" v-if="flag">
            <div class="card" style="min-width:900px;">
                <div class="header flex">
                    <div class="goHome flex">
                        <p class="title">出库明细</p>
                    </div>
                    <div class="flex">

                        <button class="submit" v-if="status ==0 "  style="width: 140px;"  @click="submitAndPrintHandle(1)">仅出库</button>
                        <button class="submit" v-if="status ==0 "  style="width: 140px;"  @click="submitAndPrintHandle(2)">出库并打印</button>
                        <button class="submit" v-if="status !=0 "  @click="printHandle">打印</button>
                        <button class="submit"  @click="toExcel">下载</button>

                        <el-icon size="22" style="margin-right: 37px; cursor: pointer;" @click="close">
                            <Close />
                        </el-icon>
                    </div>
                </div>

                <div class="printMain" id="printMain" ref="print">
                    <div>
                        <h3 class="printTitle">{{ schoolName }}卫生材料领用单</h3>
                    </div>
                    <div class="flex printPage">
                        <p class="signature">NO.{{ form.receiptCode }}</p>
                        <div class="flex Pagination">
                        </div>
                    </div>
                    <div class="flex centerBox">
                        <p>库房：物资库房</p>
                        <p>领用科室：{{ form.department }}</p>
                        <p>领用人：{{ form.requestor }}</p>
                        <p> &emsp;</p>
                    </div>
                    <div class="table_box">
                        <el-table ref="table" :data="currentList" border style="width: 100%;font-size: 14px;"
                            class="custom-table" :header-cell-style="{ 'background': '#F6F6FE', 'color': '#5B686D' }"
                            size="small" :cell-style="{ 'color': '#5B686D' }">
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="materialName" label="材料信息" min-width="200" />
                            <el-table-column prop="categoriesName" label="材料分类" />
                            <el-table-column prop="specification" label="规格" />
                            <el-table-column prop="unit" label="单位" />
                            <el-table-column prop="quantity" label="数量" />
                            <el-table-column prop="price" label="售价" />
                            <el-table-column prop="finalSellingPrice" label="售价金额">
                                <template #default="scope">
                                    <span>{{ (parseFloat(scope.row.quantity) * parseFloat(scope.row.price)).toFixed(5)
                                        }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="flex footer">
                            <p>&emsp;摘要</p>
                            <p>&emsp;填制人：{{ form.createdBy.split("(")[0] }}</p>
                            <p>&emsp;填制日期：{{ form.createdAt }}</p>
                            <p>&emsp;领料人签字：&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;</p>
                        </div>
                    </div>

                </div>

                <div style="margin: 30px 0 0 60px;">
                    <!-- <el-config-provider :locale="locale"> -->
                    <el-pagination :total="total" :page-size="pageSize" :current-page="page"
                        layout="total, prev, pager, next " @size-change="changePageSize"
                        @current-change="changeCurrentPage">
                    </el-pagination>
                    <!-- </el-config-provider> -->
                </div>
            </div>
            <div style="width: 1px;height: 100px;"></div>
        </div>
    </Transition>
</template>

<script>
import { httpService } from "@/utils/httpService";
import Icon from '@/components/Icon.vue';
import { ArrowLeft, Close } from "@element-plus/icons-vue";
import { ElConfigProvider, ElMessage, ElForm, ElLoading   ,ElMessageBox } from "element-plus";
import { getCurrentInstance } from "vue";
import { formatTime } from "@/utils/dateFormat";

import * as XLSX from "xlsx";
import XLSXS from "xlsx-style"
import { saveAs } from "file-saver";

import { Loading } from "element-plus/es/components/loading/src/service";

export default {
    name: "leftMenu",
    components: { Icon, ArrowLeft, ElMessage, ElForm, ElLoading, Close, ElConfigProvider,ElMessageBox },
    data() {
        return {
            status:1,
            flag: false,
            form: {
                receiptId:0
            },
            printList: [],
            page: 1,
            pageSize: 10,
            pageSizeAll: 10000,
            total: 0,

            submitFlag: false,
        };
    },
    computed: {
        currentList() {
            return this.printList.slice((this.page - 1) * this.pageSize, this.page * this.pageSize)
        },
    },

    mounted() {
        const instance = getCurrentInstance()
        this.schoolName = instance.appContext.config.globalProperties.$schoolName

    },
    methods: {
       
        submitAndPrintHandle(type){
            let title = "确定要出库吗？"
            if(type===1){
                title = "确定要出库吗？"
            }else{
                title = "确定要出库并打印吗？"
            }
            ElMessageBox.confirm(title, "提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    httpService("/javaApi/stockOutReceipt/confirmStockOut", "id=" + this.form.receiptId, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success("出库成功");
                                //刷新父亲路由
                                this.status = 1
                                this.$parent.getMylist()
                                if(type===2){
                                    this.printHandle()
                                }
                                this.$parent.queryById(this.form.receiptId)
                            } else {
                                ElMessage.error("出库失败，请重试！");
                            }
                        }
                    );
                })
                .catch(() => {
                });
        },
        queryById(id) {
            httpService(`/javaApi/stockOut/list/${this.page}/${this.pageSizeAll}`, { receiptId: id }, "get").then(
                (data) => {
                    if (data.list) {
                        data.list.map(item => item.createdAt = formatTime(new Date(item.createdAt)))
                        this.status = data.list[0].status
                        this.printList = data.list
                        this.total = data.total
                        this.form.requestor = data.list[0].requestor
                        this.form.receiptId = data.list[0].receiptId


                    }
                }
            );
        },

        changePageSize(size) {
            this.pageSize = size;
            this.queryById(this.form.id);
        },
        changeCurrentPage(page) {
            this.page = page;
            this.queryById(this.form.id);
        },
        close() {
            this.flag = false
            this.form = {}
            this.printList = []
            this.page = 1
            this.pageSize = 10000
            this.total = 0

        },
        printHandle() {
            const itemsPerPage = 10; // 每页最多打印的条目数
            const totalPages = Math.ceil(this.printList.length / itemsPerPage); // 总页数 
            // 将数据分成每页的组
            const paginatedList = Array.from({ length: totalPages }, (_, i) =>
                this.printList.slice(i * itemsPerPage, (i + 1) * itemsPerPage)
            );
            let totalSum = 0; // 初始化合计为 0 
            // 生成 HTML 内容
            const printContent = paginatedList.map((pageItems, pageIndex) => {
                // 计算本页小计
                const pageSum = pageItems.reduce((sum, item) => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return sum + itemTotal;
                }, 0);
                totalSum += pageSum; // 累加到总计 
                return `
                    <div class="table-container">
                        <p class="pTitle">${this.schoolName}卫生材料领用单</p>
                        <div class="table-header">
                            <div>NO.${this.form.receiptCode}</div> <!-- 页码递增 -->
                            <div>第 ${pageIndex + 1} 页/共 ${totalPages} 页</div>
                        </div>
                        <div class="table-info">
                            <span>库房: 物资库房</span>
                            <span>领用科室: ${this.form.department}</span>
                            <span>领用人: ${this.form.requestor}</span>
                            <span> </span>
                        </div>
                        <table style="">
                            <thead>
                                <tr>
                                    <td>材料信息</td>
                                    <td>材料分类</td>
                                    <td>规格</td>
                                    <td>单位</td>
                                    <td>数量</td>
                                    <td>售价</td>
                                    <td>售价金额</td>
                                </tr>
                            </thead>
                            <tbody>
                                ${pageItems.map(item => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return `
                            <tr>
                                <td>${item.materialName}</td>
                                <td>${item.categoriesName}</td>
                                <td>${item.specification}</td>
                                <td>${item.unit}</td>
                                <td>${item.quantity}</td>
                                <td>${item.price}</td>
                                <td>${itemTotal.toFixed(5)}</td>  
                            </tr>
                        `;
                }).join('')}
                                <tr>
                                    <td>本页小计</td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td>${pageSum.toFixed(5)}</td>
                                </tr>
                                <tr>
                                    <td>合&emsp;计</td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                    <td>${totalSum.toFixed(5)}</td>
                                </tr> 
                            </tbody>
                        </table>
                        <div class="table-footer">
                            <div>摘要</div>
                            <div>填制人: ${this.form.createdBy.split("(")[0]}</div>
                            <div>填制日期: ${this.form.createdAt}</div>
                            <div>领料人签字: &emsp; &emsp; &emsp; &emsp; &emsp; &emsp;</div>
                        </div>
                    </div>
                    <div style="page-break-after: always;"></div> <!-- 确保分页 -->
                `;
            }).join('');

            // 创建打印窗口
            const WinPrint = window.open('', '', 'width=800,height=600,scrollbars=yes');
            WinPrint.document.write(`
                <html>
                <head>
                    <title>打印</title>
                    <style>
                        @media print { 
                            @page {
                                margin: 30px 20mm;
                            }
                            body {
                                margin: 0;
                                font-family: Arial, sans-serif;
                            }
                            .table-container {
                                width: 100%;
                                text-align: center;
                                // page-break-before: always; /* 强制每个新内容开始时分页 */
                            }
                            .table-container:last-child {
                                page-break-after: auto; /* 最后一页不分页 */
                            }
                            .table-header,
                            .table-info,
                            .table-footer {
                                display: flex;
                                justify-content: space-between; 
                            }
                            .pTitle {
                                font-size: 20px;
                                font-weight: 400;
                                text-align: center;
                            }
                            table {
                                width: calc(100% - 4pt);
                                margin:0 2pt;
                                border: 1pt solid #000;
                                border-collapse: collapse; 
                            }
                            th, td {
                                border: 1pt solid #000; 
                                // text-align: center;
                            }
                            tr:nth-child(even) {
                                background-color: #f2f2f2; /* 隔行变色 */
                            }
                        }
                    </style>
                </head>
                <body>
                    ${printContent}
                </body>
                </html>
            `);
            WinPrint.document.close();
            WinPrint.print();
            WinPrint.close();
        },

        toExcel() {
            const data = this.printList; // 数据列表
            const rowsPerPage = 10; // 每页显示的行数
            const sheetData = [];
            const merges = []; // 合并单元格信息
            let pageCount = 1;

            const title = `${this.schoolName}卫生材料领用单`
            const number = `NO.Y${this.form.receiptCode}`
            const page = `第一页/共三页`
            const department = `领用科室: ${this.form.department}`
            const personal = `领用人: ${this.form.requestor}`
            const teacher = `填制人: ${this.form.createdBy.split("(")[0]}`
            const time = `填制日期: ${this.form.createdAt}`

            data.forEach((item, index) => {
                // 每页开始时添加表头
                if (index % rowsPerPage === 0) {
                    const startRow = sheetData.length;

                    // 表头部分
                    sheetData.push([title, "", "", "", "", "", ""]);
                    sheetData.push([
                        number,
                        "",
                        "",
                        `第${pageCount}页/共${Math.ceil(data.length / rowsPerPage)}页`,
                        "",
                        "",
                        ""
                    ]);
                    sheetData.push([
                        "库房：物资库房",
                        "",
                        department,
                        "",
                        personal,
                        "",
                        ""
                    ]);
                    sheetData.push([
                        "材料信息",
                        "材料分类",
                        "规格",
                        "单位",
                        "数量",
                        "售价",
                        "售价金额"
                    ]);

                    // 添加表头的合并范围
                    merges.push(
                        { s: { r: startRow, c: 0 }, e: { r: startRow, c: 6 } }, // 标题合并
                        { s: { r: startRow + 1, c: 0 }, e: { r: startRow + 1, c: 2 } },
                        { s: { r: startRow + 1, c: 3 }, e: { r: startRow + 1, c: 6 } },
                        { s: { r: startRow + 2, c: 0 }, e: { r: startRow + 2, c: 1 } },
                        { s: { r: startRow + 2, c: 2 }, e: { r: startRow + 2, c: 3 } },
                        { s: { r: startRow + 2, c: 4 }, e: { r: startRow + 2, c: 5 } }
                    );

                    pageCount++;
                }

                // 添加数据行
                sheetData.push([
                    item.materialName,
                    item.categoriesName,
                    item.specification,
                    item.unit,
                    item.quantity,
                    item.price,
                    item.quantity * item.price
                ]);

                // 添加表尾
                if ((index + 1) % rowsPerPage === 0 || index === data.length - 1) {
                    const footerStartRow = sheetData.length;

                    sheetData.push([
                        "摘要",
                        teacher,
                        "",
                        time,
                        "",
                        "领料人签字：",
                        "",
                    ]);

                    merges.push(
                        { s: { r: footerStartRow, c: 0 }, e: { r: footerStartRow, c: 0 } },
                        { s: { r: footerStartRow, c: 1 }, e: { r: footerStartRow, c: 2 } },
                        { s: { r: footerStartRow, c: 3 }, e: { r: footerStartRow, c: 4 } },
                        { s: { r: footerStartRow, c: 5 }, e: { r: footerStartRow, c: 6 } },
                    );

                    // 添加间隔行
                    sheetData.push([], []);
                }
            });

            // 生成工作表
            let ws = XLSX.utils.aoa_to_sheet(sheetData);
            console.log('ws', ws);

            // 添加合并单元格信息
            ws["!merges"] = merges;

            // 设置边框和样式
            ws = this.setExlStyle(ws);

            // 导出 Excel
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "分组表");

            const excelData = XLSX.write(wb, { bookType: "xlsx", type: "array" });


            var table = XLSXS.write(wb, {
                type: "buffer"
            });
            try {
                saveAs(
                    new Blob([table], { type: "application/octet-stream" }),
                    `${title}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, table);
            }
            return table;



            // saveAs(new Blob([excelData], { type: "application/octet-stream" }), `分页表格.xlsx`);
        },

        setExlStyle(data) {
            const borderAll = { // 单元格外侧框线
                top: { style: "thin" },
                bottom: { style: "thin" },
                left: { style: "thin" },
                right: { style: "thin" }
            };

            // 获取工作表的范围
            const range = XLSX.utils.decode_range(data["!ref"]);

            for (let R = range.s.r; R <= range.e.r; ++R) {
                for (let C = range.s.c; C <= range.e.c; ++C) {
                    const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!data[cellAddress]) {
                        data[cellAddress] = { v: "" }; // 如果单元格没有内容，设置为空字符串
                    } else {
                        data[cellAddress].s = {
                            border: borderAll, // 添加边框
                            alignment: {
                                horizontal: "center", // 水平居中对齐
                                vertical: "center"    // 垂直居中对齐
                            }
                        };
                    }
                }
            }

            // 设置列宽
            data["!cols"] = [
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 }
            ];

            return data;
        },



    },
}
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.flex {
    display: flex;
    align-items: center;
}

.contain {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.35);
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    overflow-y: auto;
}

.card {
    width: 60%;
    height: calc(100vh - 100px);
    background-color: #fff;
    border-radius: 13px;
    margin-top: 50px;
    margin-bottom: 50px;
}

.table_box {
    height: calc(100vh - 400px);
    overflow: auto;
}

.header {
    justify-content: space-between;
    height: 65px;
    border-bottom: 1px solid #D6DBE2;
}

.header .title {
    color: #000000;
    font-size: 18px;
    font-weight: bold;
    margin-left: 32px;
}

.submit {
    width: 77px;
    height: 38px;
    background-color: #6F72FF;
    border-radius: 10px;
    border: none;
    margin-right: 32px;
    color: #fff;
    font-size: 15px;
    cursor: pointer;
}

.main {
    /* width: 50vw; */
    padding: 23px 60px 0 60px;
    margin: 10px auto 0;
    /* display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    align-content: flex-start; */
    overflow-y: auto;
}

.main_li {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.inputBox {
    width: calc((100% - 90px) / 3);
    /* width: calc((100% - 100px) / 2); */
    margin-bottom: 15px;
}

.inputName {
    color: #5B686D;
    font-size: 15px;
    margin-bottom: 5px;
}

.inputName span {
    color: #FF0000;
    font-size: 15px;
    margin-bottom: 5px;
}

.myInput {
    width: calc(100% - 19px);
    height: 42px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    outline: none;
    font-size: 15px;
    color: #000;
    padding-left: 19px;
}

.myInput::placeholder {
    color: #A9B6BB;
}

.myText {
    width: calc(100% - 36px);
    height: 150px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    resize: none;
    outline: none;
    padding: 18px;
    font-size: 15px;
    color: #000;
}

.myText::placeholder {
    color: #A9B6BB;
}


input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

/* 对于Firefox */
input[type="number"] {
    -moz-appearance: textfield;
}



.select ::v-deep .el-tooltip__trigger {
    width: 100%;
    height: 44px;
    border-radius: 10px;
}

.el-select-dropdown__item {
    padding-left: 15px;
}

::v-deep .el-select {
    --el-color-primary: #D6DBE2;
}



.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}
</style>

<style>
.printMain {
    margin: 10px 60px 0;
}

.printTitle {
    text-align: center;
    margin-bottom: 10px;
    color: #2B2B2B;
    font-size: 17px;
}

.printPage {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.signature {
    color: #2B2B2B;
    font-size: 17px
}

.Pagination {
    color: #2B2B2B;
    font-size: 17px;
    display: flex;
    align-items: center;
}

.nextBtn {
    color: #6F72FF;
    margin-left: 30px;
}

.centerBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.footer {
    color: #959EA1;
    font-size: 15px;
    margin-top: 10px;
    display: flex !important;
    align-items: center !important;
    justify-content: space-between;
}

.p1 {
    /* width: calc(100% / 7); */
}

.p2 {
    /* width: calc((100% / 7) * 2); */
    white-space: nowrap;
}


.applyBtn {
    width: 100px;
    line-height: 35px;
    border-radius: 10px;
    font-size: 15px;
    background-color: #6F72FF;
    color: #fff;
    text-align: center;
    cursor: pointer;
}
</style>